import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;

import java.io.*;
import java.sql.DriverManager;
import java.sql.SQLException;

/**
 * @version : V1.0
 * @program: maven
 * @ClassName: Imge
 * @Description:
 * @Author: chenxiejia
 * @Date: 2022/2/17 10:24
 */
public class Imge {
    @Test
    @DisplayName("图片存储")
    void m1() throws SQLException, FileNotFoundException {
        File file = new File("F:/chen.jpg");
        var fn = file.getName().toLowerCase();
        FileInputStream is = new FileInputStream(file);
        var conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/db1", "root", "admin");
        var sta = conn.prepareStatement("insert into db1.t7 value (null,?,?)");
        sta.setString(1, fn);
        sta.setBlob(2, is);
        var rs = sta.executeUpdate();
        if (rs > 0) {
            System.out.println("插入图片成功");
        } else {
            System.out.println("插入失败");
        }
    }

    @Test
    @DisplayName("读取数据库存储图片")
    void m2() throws SQLException, IOException {
        var conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/db1", "root", "admin");
        var sta = conn.prepareStatement("select * from db1.t7 where id=1");
        var rs = sta.executeQuery();
        while (rs.next()) {
            String fna = rs.getString(2);
            FileOutputStream fos = new FileOutputStream(new File(fna));
            rs.getBlob(3).getBinaryStream().transferTo(fos);
            fos.flush();
            Runtime.getRuntime().exec("cmd /k start chen.jpg");
        }
    }
}
